//
//  CZEmoticonView.swift
//  Weibo24
//
//  Created by apple on 16/3/7.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit

/*
    界面 -- 
    功能
*/
let CZEmoticonViewReuseIdentifier = "CZEmoticonViewReuseIdentifier"
class CZEmoticonView: UIView ,UICollectionViewDataSource,CZEmoticonToolBarViewDelegate{

    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
        
        setupCollectionView()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK:--添加控件和设置属性
    private func setupUI(){
    
        //
        addSubview(collectionView)
        addSubview(toolBarView)
        
        toolBarView.backgroundColor = randomColor()
        
        //设置约束 左边,上边,右边,下边是 toolBarView的顶部
        collectionView.snp_makeConstraints { (make) -> Void in
        
            make.left.equalTo(self.snp_left)
            make.top.equalTo(self.snp_top)
            make.right.equalTo(self.snp_right)
            make.bottom.equalTo(toolBarView.snp_top)
            
        }
        
        // 左边,底部,右边,高度
        toolBarView.snp_makeConstraints { (make) -> Void in
            
            make.left.equalTo(self.snp_left)
            make.right.equalTo(self.snp_right)
            make.bottom.equalTo(self.snp_bottom)
            make.height.equalTo(40)
            
        }
        
    }
    
    //MARK:--设置collectionView的属性
    private func setupCollectionView(){
    
        //设置数据源方法
        
        collectionView.dataSource = self
        
        //注册cell
        collectionView.registerClass(CZEmoticonCollectionViewCell.self, forCellWithReuseIdentifier: CZEmoticonViewReuseIdentifier)
        //改变滑动方向
        flowLayout.scrollDirection = .Horizontal
        
        //去掉滚动的提示
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.showsVerticalScrollIndicator = false
        
        collectionView.pagingEnabled = true
        
        
        
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        //设置item
        flowLayout.itemSize = CGSizeMake(kUIScreenWidth,collectionView.frame.height)
        flowLayout.minimumInteritemSpacing = 0
        flowLayout.minimumLineSpacing = 0
    }
    
    //MARK:--懒加载
    
    //上边 是用 UICollectionView实现
    private lazy var flowLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    
    private lazy var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.flowLayout)
    
    // 下边 是自定义的 UIView
    private lazy var toolBarView: CZEmoticonToolBarView = {
    
        let toolbar = CZEmoticonToolBarView()
        //设置代理
        toolbar.delegate = self
        
        return toolbar
    }()
    

}

//MARK:-- CZEmoticonToolBarViewDelegate
extension CZEmoticonView{

    func didToolBarItemClick(type: CZEmoticonToolBarButtonType) {
        
        switch type{
        
        case .Recent:
            let indexPath = NSIndexPath(forItem: 0, inSection: 0)
            collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
        case .Default:
            let indexPath = NSIndexPath(forItem: 0, inSection: 1)
            collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
        case .Emoji:
            let indexPath = NSIndexPath(forItem: 0, inSection: 2)
            collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
        case .Lxh:
            let indexPath = NSIndexPath(forItem: 0, inSection: 3)
            collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
            
        default : break
        }
        
    }
    
}
//MARK:-- UICollectionViewDataSource
extension CZEmoticonView {

    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        
//        CZEmoticonManager.readEmotions()
        // return 4  不建议大家直接写数字
        
        return CZEmoticonManager.getAllEmoticons().count
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return CZEmoticonManager.getAllEmoticons()[section].count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(CZEmoticonViewReuseIdentifier, forIndexPath: indexPath) as! CZEmoticonCollectionViewCell
        
        //也可以根据数组对应的下标去获取表情 
//       cell.label.text = "第\(indexPath.section)部分 第\(indexPath.row)item"
        
        cell.emoticons = CZEmoticonManager.getAllEmoticons()[indexPath.section][indexPath.item]
        
        return cell
    }
    
}

//自定义一个cell,然后在cell里放一个label
class CZEmoticonCollectionViewCell: UICollectionViewCell{

    /*
        CollectionViewCell是由重用的
        1.创建20个表情[表情用Button实现]
        2.添加到cell[设置frame]
        3.把这20个表情,放置在一个重用数组里[定义一个数组]
        4.赋值的时候,直接去修改 表情的图片 [需要遍历]
    */
    
    var emoticons: [CZEmoticon]?{
    
        didSet{
        
            // 遍历 表情数组,拿到图片的路径或者emoji来显示
            /*
                emoticons!.enumerate() -> 这个就是对数组进行遍历
                (index,emoticon) ->  (索引,值)
            */
            
            /*
                最近的表情重用怎么解决
                我们可以通过隐藏按钮
            */
            
            for (_,button) in reuserButtons.enumerate(){
                button.hidden = true
            }
            
            
            
            for (index,emoticon) in emoticons!.enumerate() {
            
                // 根据索引,拿到对应的button
                let button = reuserButtons[index]
                //在这里传值
                button.emoticon = emoticon
                //知道绝对路径 
                /*
                    注意,你一定要打断点看一下 iamgePath对不对
                    Optional(\"/Users/apple/Library/Developer/CoreSimulator/Devices/5DAC0877-1F80-453E-93E7-9F0A9657EFA1/data/Containers/Bundle/Application/CA199B8E-F03E-4355-AEF0-BC153D210012/Weibo24.app/Emoticons.bundle/com.sina.default\")/Optional(\"d_zuiyou.png\")
                
                
                */
                /*
                    针对重用问题,需要清空
                */
               
            }
            
        }
        
    }
    
    private lazy var reuserButtons: [CZEmoticonButton] = [CZEmoticonButton]()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
    
        backgroundColor = randomColor()
        
//        contentView.addSubview(label)
//        
//        label.snp_makeConstraints { (make) -> Void in
//            make.center.equalTo(contentView.snp_center)
//        }
        
        addEmotions()
    }
    
    //MARK:-- 添加表情
    private func addEmotions(){
    
        // 表情的宽
        let width = frame.size.width / 7
        // 表情的高
        let height = frame.size.height / 3
        
        for i in 0..<20{
        
            let button = CZEmoticonButton(type: UIButtonType.Custom)
            //列
            let col = i%7
            //行
            let row = i/7
            
            button.frame = CGRectMake(CGFloat(col) * width, CGFloat(row) * height, width, height)
            
            button.setTitleColor(UIColor.redColor(), forState: UIControlState.Normal)
            
            button.addTarget(self, action: "emoticonClick:", forControlEvents: UIControlEvents.TouchUpInside)
            
//            button.setTitle("\(i)", forState: UIControlState.Normal)
            
            contentView.addSubview(button)
            
            reuserButtons.append(button)
        }
        
        //添加删除按钮
        //设置frame
        deleteButton.frame = CGRectMake(6*width, 2*height, width, height)
        contentView.addSubview(deleteButton)
    }
    //MARK:--按钮的点击
    @objc private func emoticonClick(button: CZEmoticonButton){
    
        /*
            视图经过了 CZPublishViewController -> CZEmoticonView -> CZEmoticonCollectionViewCell
            回调传值由 C -> A ,所以我们选择通知
        
        
        */
        //发送通知
        NSNotificationCenter.defaultCenter().postNotificationName(kNotificationEmoticonTransform, object: nil, userInfo: ["emoticon":button.emoticon!])
        
        // 点击按钮, 来获得按钮对应的表情
        
        // 把点击的表情,放置在最近的数组
        // 这样做可以实现,但是不建议大家这么做?
//        CZEmoticonManager.recentEmoticons.append(button.emoticon!)
        
        CZEmoticonManager.addRecentEmoticon(button.emoticon)
    }
    
    //MARK:--懒加载
    private lazy var label: UILabel = {
    
        let label = UILabel()
        
        label.font = UIFont.systemFontOfSize(18)
        
        
        return label
    }()

    
    private lazy var deleteButton: CZEmoticonButton = {
    
        let button = CZEmoticonButton(type: UIButtonType.Custom)
        
        button.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
        
        button.addTarget(self, action: "emoticonClick:", forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
        
    }()

}

